package cn.youwan.market;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import cn.youwan.market.entity.AppListBean;
import cn.youwan.market.http.YouwanSession;
import cn.youwan.market.message.YouwanMessage;
import cn.youwan.market.utils.Const;
import cn.youwan.market.utils.PackageManagerUtils;
import cn.youwan.market.utils.UserPreference;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;

public class MyApplication extends Application {
	private Map<String, PackageInfo> InstallApps;// 已经安装的应用
	private AppListBean upGradeApps; // 可升级应用
	private List<String> hotSearch;
    public static MyApplication instance;
	public String sha="呵呵";
	public Map<String, PackageInfo> getInstallApps() {
		return InstallApps;
	}
	
	

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		instance=this;
		// 初始化Session
		YouwanSession.getYangSession(this);
		// 获取已经安装的App
		getAllInstallAppsTask();
		// 初始化下载网络设置提醒
		UserPreference.ensureIntializePreference(this);
		Const.DownLoadTip = UserPreference.read("downtip", true);
		// 获取首页搜索热词
		getHotSearch();
		// 获取版本号
		savePackageVersion();
	}

	private void savePackageVersion() {
		try {
			String version = PackageManagerUtils.getVersion(this);
			UserPreference.save("appversion", version);
			String versionNum = PackageManagerUtils.getVersionNum(this);
			UserPreference.save("versionNum", versionNum);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void refrashInstallApp() {
		getAllInstallAppsTask();
	}

	private void getAllInstallAppsTask() {
		new AsyncTask<Void, Void, Void>() {
			protected void onPreExecute() {
			};

			@Override
			protected Void doInBackground(Void... params) {
				getAllInstallApps(MyApplication.this);
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				Log.v("g0", "go");
				if (InstallApps.size() != 0)
					getUpgradeApplications();
			}
		}.execute();
	}

	private void getAllInstallApps(Context context) {
		InstallApps = new HashMap<String, PackageInfo>();
		PackageManager pManager = context.getPackageManager();
		// 获取手机内所有应用
		List<PackageInfo> packlist = pManager.getInstalledPackages(0);
		Log.v("ddd", System.currentTimeMillis() + "");
		for (int i = 0; i < packlist.size(); i++) {
			PackageInfo pak = (PackageInfo) packlist.get(i);

			InstallApps.put(pak.packageName, pak);
			// 判断是否为非系统预装的应用程序
			// 这里还可以添加系统自带的，这里就先不添加了，如果有需要可以自己添加
			// if()里的值如果<=0则为自己装的程序，否则为系统工程自带
			if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
				// 添加自己已经安装的应用程序
				
			}
		}
		Log.v("eeeee", System.currentTimeMillis() + "");
	}

	private void getUpgradeApplications() {
		new AsyncTask<Void, Void, Void>() {
			protected void onPreExecute() {
			};

			@Override
			protected Void doInBackground(Void... params) {
				YouwanMessage message = new YouwanMessage(MyApplication.this);
				String data = getDatas();
				//upGradeApps = message.getUpgrade(data);
				System.out.println("upGradeApps = " + upGradeApps);
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
			}
		}.execute();
	}

	private String getDatas() {
		try {
			JSONArray array = new JSONArray();
			List<PackageInfo> infos = new ArrayList<PackageInfo>(
					InstallApps.values());
			for (int i = 0; i < infos.size(); i++) {
				JSONObject json = new JSONObject();
				json.put(
						"name",
						infos.get(i).applicationInfo.loadLabel(
								getPackageManager()).toString());
				json.put("package", infos.get(i).packageName);
				json.put("app_version_code",
						String.valueOf(infos.get(i).versionCode));

				// 调试用
				// if
				// (infos.get(i).applicationInfo.loadLabel(getPackageManager())
				// .toString().contains("360")) {
				// System.out.println("360 : "
				// + String.valueOf(infos.get(i).versionCode) + ";"
				// + infos.get(i).versionName + ","
				// + infos.get(i).packageName);
				// }
				array.put(json);
			}
			return array.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public AppListBean getUpGradeApps() {
		return upGradeApps;
	}

	private void getHotSearch() {
		new AsyncTask<Void, Void, Void>() {
			protected void onPreExecute() {
			};

			@Override
			protected Void doInBackground(Void... params) {
				YouwanMessage message = new YouwanMessage(getApplicationContext());
				hotSearch = message.getSearchHot();
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
			}
		}.execute();
	}

	public List<String> getHotSearchs() {
		return hotSearch;
	}
}
